﻿using Inaction.Business.Security;
using Inaction.Security;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Inaction.Extensions.Security
{
    [Serializable]
    public class SecurityPrincipal : Principal
    {
        public static UserIdentity UserIdentity
        {
            get { return Instance == null ? null : Instance.Identity as UserIdentity; }
        }

        private SecurityPrincipal() { }

        public SecurityPrincipal(UserInfo user)
        {
            var identity = new UserIdentity();
            identity.Id = user.Id;
            identity.DepartmentId = user.DepartmentId;
            identity.IsAuthenticated = true;
            identity.Name = user.Name;
            identity.UserNumber = user.Number;
            identity.Type = user.UserType;
            identity.Token = DEncrypt.AESEncrypt(identity.UserNumber,Inaction.AppConfig.Instance.CrypKey);
            roles = GetRoles(identity.Id);
            base.Identity = identity; 
        }

        private IEnumerable<IRole> GetRoles(Guid? userId)
        {
            string sql = Mapping.EntitySqlStatement.GetSelectSql<UserRoleV>();
            sql += @" Where "
                + UserRoleV.UserIdProperty.Column.FormatName + " = " + Inaction.DbProvider.Instance.ParaFix + UserRoleV.UserIdProperty.Name;

            using (var command = DbProvider.CreateCommand(sql))
            {
                DbProvider.AddParameter(command, UserRoleV.UserIdProperty.Name, userId);
                var reader = command.ExecuteReader();
                List<UserRoleV> roles = new List<UserRoleV>();
                while (reader.Read())
                {
                    var role = new UserRoleV();
                    role.Init(reader);
                    roles.Add(role);
                }
                return roles;
            }
        }

        private IEnumerable<IRole> roles;
        public override IEnumerable<IRole> GetOwnedRoles()
        {
            return roles;
        }
        public override bool IsInRole(string role)
        {
            return roles.Any(p => p.Code == role || p.Id.ToString().Equals(role,StringComparison.OrdinalIgnoreCase));
        }
    }
}